package bytestream;

import java.io.*;

public class DirectoryCopyDemo {
    //复制文件
    //src:源文件 source 源
    //dest:目标文件 destination 目标
    public static void copy(File src, File dest) {
        BufferedInputStream bin = null;  //buffered input  输入流
        BufferedOutputStream bout = null; //buffered output 输出流
        int len = -1; //每次读取的字节的个数
        byte[] buff = new byte[1024]; //一个kb的缓冲区。
        try {
            bin = new BufferedInputStream(new FileInputStream(src));
            bout = new BufferedOutputStream(new FileOutputStream(dest));
            //一头读，一头写
            while ((len = bin.read(buff, 0, buff.length)) != -1) {
                bout.write(buff, 0, len);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (bin != null) {
                    bin.close();
                    bin = null;
                }
                if (bout != null) {
                    bout.close();
                    bout = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void directoryCopy(File srcDir, File destDir) {
        //源目录肯定存在，目标目录不一定存在。
        try {
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            //遍历
            File[] files = srcDir.listFiles();
            for (File f : files) {
                //是不是目录
                if (f.isDirectory()) {
                    //递归，
                    File tempDir = new File(destDir, f.getName());
                    directoryCopy(f, tempDir);
                } else {
                    File tempFile = new File(destDir, f.getName());
                    copy(f, tempFile);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        File srcDir = new File("E:" + File.separator + "web_lesson");
        File destDir = new File("H:" + File.separator + "web_lesson");
        directoryCopy(srcDir, destDir);
    }
}
